<template>
  <view class="llm-chat">
    <view class="llm-header">
      <text class="llm-title">🤖 AI参数调整助手</text>
      <text class="llm-subtitle">自然语言调整水文模型参数</text>
    </view>
    
    <!-- 会话未开始提示 -->
    <view v-if="!sessionId || sessionId === 'null'" class="session-warning">
      <text class="warning-icon">⚠️</text>
      <view class="warning-content">
        <text class="warning-title">预报会话未开始</text>
        <text class="warning-text">请先选择预报方案并加载参数，才能使用AI助手调整参数。</text>
      </view>
    </view>

    <!-- 对话历史 -->
    <view class="llm-messages" ref="messagesContainer">
      <view 
        v-for="(msg, index) in messages" 
        :key="index"
        class="llm-message"
        :class="msg.role"
      >
        <view class="msg-avatar">
          <text class="avatar-emoji">{{ msg.role === 'user' ? '👤' : '🤖' }}</text>
        </view>
        <view class="msg-content">
          <view class="msg-header">
            <text class="msg-sender">{{ msg.role === 'user' ? '我' : 'AI助手' }}</text>
            <text class="msg-time">{{ formatTime(msg.timestamp) }}</text>
          </view>
          
          <!-- 用户消息 -->
          <view v-if="msg.role === 'user'" class="msg-text user-text">
            {{ msg.content }}
          </view>
          
          <!-- AI消息 -->
          <view v-else class="msg-text ai-text">
            <!-- AI回复 -->
            <view class="ai-section">
              <text class="ai-reply">{{ msg.content }}</text>
            </view>
            
            <!-- 参数变化 -->
            <view v-if="msg.parameterChanges" class="param-changes">
              <view class="section-title">
                <text class="title-icon">📝</text>
                <text class="title-text">参数变化</text>
              </view>
              <view class="param-list">
                <view 
                  v-for="(value, key) in msg.parameterChanges" 
                  :key="key"
                  class="param-item"
                >
                  <text class="param-key">{{ formatParamKey(key) }}</text>
                  <text class="param-arrow">→</text>
                  <text class="param-value">{{ value }}</text>
                </view>
              </view>
            </view>
            
            <!-- 解释说明 -->
            <view v-if="msg.explanation" class="explanation">
              <view class="section-title">
                <text class="title-icon">💡</text>
                <text class="title-text">说明</text>
              </view>
              <text class="explanation-text">{{ msg.explanation }}</text>
            </view>
            
            <!-- 应用状态 -->
            <view v-if="msg.applyStatus" class="apply-status" :class="msg.applyStatus.success ? 'success' : 'error'">
              <text class="status-icon">{{ msg.applyStatus.success ? '✅' : '❌' }}</text>
              <text class="status-text">{{ msg.applyStatus.message }}</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- AI思考中 -->
      <view v-if="isThinking" class="llm-message assistant thinking">
        <view class="msg-avatar">
          <text class="avatar-emoji">🤖</text>
        </view>
        <view class="msg-content">
          <view class="thinking-indicator">
            <view class="thinking-dots">
              <span class="dot"></span>
              <span class="dot"></span>
              <span class="dot"></span>
            </view>
            <text class="thinking-text">{{ thinkingText }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 输入区域 -->
    <view class="llm-input-container">
      <textarea 
        class="llm-input"
        v-model="inputText"
        placeholder="例如：请将SA0改为10，A参数增加0.1"
        :disabled="isThinking"
        @confirm="sendMessage"
      />
      <button 
        class="llm-send-btn"
        :class="{ disabled: !canSend }"
        :disabled="!canSend"
        @click="sendMessage"
      >
        <text class="btn-icon">{{ isThinking ? '⏳' : '✈️' }}</text>
        <text class="btn-text">{{ isThinking ? '处理中...' : '发送' }}</text>
      </button>
    </view>
  </view>
</template>

<script>
import { ref, computed, nextTick } from 'vue'
import { v4 as uuidv4 } from 'uuid'

export default {
  name: 'LLMChat',
  props: {
    sessionId: {
      type: String,
      required: true
    },
    currentParams: {
      type: Object,
      required: true
    }
  },
  emits: ['params-updated'],
  setup(props, { emit }) {
    const messages = ref([])
    const inputText = ref('')
    const isThinking = ref(false)
    const thinkingText = ref('AI正在思考...')
    const messagesContainer = ref(null)
    const conversationId = ref(uuidv4())

    const canSend = computed(() => {
      return inputText.value.trim().length > 0 && 
             !isThinking.value && 
             props.sessionId && 
             props.sessionId !== 'null'
    })

    // 格式化参数键名
    const formatParamKey = (key) => {
      const parts = key.split('.')
      if (parts.length === 2) {
        return `${parts[0] === 'initial_state' ? '初始状态' : '参数'}.${parts[1]}`
      }
      return key
    }

    // 格式化时间
    const formatTime = (timestamp) => {
      const date = new Date(timestamp)
      return date.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    }

    // 滚动到底部
    const scrollToBottom = () => {
      nextTick(() => {
        const container = document.querySelector('.llm-messages')
        if (container) {
          container.scrollTop = container.scrollHeight
        }
      })
    }

    // 发送消息
    const sendMessage = async () => {
      if (!canSend.value) return
      
      // 检查会话是否有效
      if (!props.sessionId || props.sessionId === 'null') {
        messages.value.push({
          role: 'assistant',
          content: '⚠️ 预报会话未开始，无法使用AI助手。',
          explanation: '请先选择预报方案并加载参数后再使用AI助手调整参数。',
          timestamp: new Date().toISOString(),
          applyStatus: {
            success: false,
            message: '会话无效'
          }
        })
        scrollToBottom()
        return
      }

      const userMessage = inputText.value.trim()
      
      // 添加用户消息
      messages.value.push({
        role: 'user',
        content: userMessage,
        timestamp: new Date().toISOString()
      })
      
      inputText.value = ''
      scrollToBottom()
      
      // 开始AI处理
      isThinking.value = true
      thinkingText.value = 'AI正在分析您的需求...'
      
      try {
        // 1. 调用LLM API
        thinkingText.value = '正在调用AI模型...'
        const llmResponse = await callLLMAPI(userMessage)
        
        // 检查API返回的success标志
        if (llmResponse.success === false) {
          // API返回失败
          messages.value.push({
            role: 'assistant',
            content: llmResponse.message || '处理请求失败',
            explanation: llmResponse.explanation || '会话可能已失效或不存在',
            timestamp: new Date().toISOString(),
            applyStatus: {
              success: false,
              message: llmResponse.message || '请求失败'
            }
          })
          scrollToBottom()
          return
        }
        
        // 2. 解析LLM响应
        thinkingText.value = '正在解析AI回复...'
        const aiMessage = {
          role: 'assistant',
          content: llmResponse.message || 'AI处理完成',
          parameterChanges: llmResponse.parameter_changes,
          explanation: llmResponse.explanation,
          timestamp: new Date().toISOString()
        }
        
        messages.value.push(aiMessage)
        scrollToBottom()
        
        // 3. 应用参数变化
        if (llmResponse.parameter_changes && 
            Object.keys(llmResponse.parameter_changes).length > 0 &&
            llmResponse.current_parameters) {
          thinkingText.value = '正在应用参数变化...'
          const applyResult = await applyParameterChanges(llmResponse.current_parameters)
          
          // 更新最后一条消息的应用状态
          const lastMsg = messages.value[messages.value.length - 1]
          lastMsg.applyStatus = applyResult
          
          // 通知父组件参数已更新
          if (applyResult.success) {
            emit('params-updated', llmResponse.current_parameters)
          }
        } else if (!llmResponse.parameter_changes || Object.keys(llmResponse.parameter_changes || {}).length === 0) {
          // 没有参数变化
          const lastMsg = messages.value[messages.value.length - 1]
          lastMsg.applyStatus = {
            success: true,
            message: 'AI已理解，但没有需要修改的参数'
          }
        }
        
      } catch (error) {
        console.error('LLM处理失败:', error)
        
        let errorMessage = '抱歉，处理您的请求时出现了错误。'
        let errorExplanation = error.message || '未知错误'
        
        // 特殊处理常见错误
        if (error.message && error.message.includes('会话不存在')) {
          errorMessage = '⚠️ 预报会话已失效或不存在'
          errorExplanation = '当前会话可能已经失效。请尝试重新选择预报方案或修改参数以创建新的会话。'
        } else if (error.message && error.message.includes('Failed to fetch')) {
          errorMessage = '⚠️ 网络连接失败'
          errorExplanation = '无法连接到AI服务器，请检查网络连接后重试。'
        }
        
        messages.value.push({
          role: 'assistant',
          content: errorMessage,
          explanation: errorExplanation,
          timestamp: new Date().toISOString(),
          applyStatus: {
            success: false,
            message: '处理失败'
          }
        })
        
        scrollToBottom()
      } finally {
        isThinking.value = false
      }
    }

    // 调用LLM API
    const callLLMAPI = async (message) => {
      const response = await fetch('https://ws.waterism.tech:8091/api/execute', {
        method: 'POST',
        headers: {
          'accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          session_id: props.sessionId,
          question: message
        })
      })

      if (!response.ok) {
        const errorText = await response.text()
        throw new Error(`LLM API调用失败: ${response.status} - ${errorText}`)
      }

      const result = await response.json()
      
      // 检查API返回的success标志
      if (result.success === false) {
        // 如果API明确返回失败，抛出错误（包含服务器返回的message）
        throw new Error(result.message || '会话不存在')
      }
      
      return result
    }

    // 比对参数并生成updates
    const generateUpdates = (newParams) => {
      const updates = {
        initial_state: {},
        parameters: {}
      }

      // 比对 initial_state
      if (newParams.initial_state) {
        for (const key in newParams.initial_state) {
          if (props.currentParams.initial_state[key] !== newParams.initial_state[key]) {
            updates.initial_state[key] = newParams.initial_state[key]
          }
        }
      }

      // 比对 parameters
      if (newParams.parameters) {
        for (const key in newParams.parameters) {
          // 跳过 monthlyPET（通常不通过LLM修改）
          if (key === 'monthlyPET') continue
          
          if (props.currentParams.parameters[key] !== newParams.parameters[key]) {
            updates.parameters[key] = newParams.parameters[key]
          }
        }
      }

      // 如果某个分类没有变化，删除空对象
      if (Object.keys(updates.initial_state).length === 0) {
        delete updates.initial_state
      }
      if (Object.keys(updates.parameters).length === 0) {
        delete updates.parameters
      }

      return updates
    }

    // 应用参数变化
    const applyParameterChanges = async (newParams) => {
      try {
        const updates = generateUpdates(newParams)
        
        if (Object.keys(updates).length === 0) {
          return {
            success: true,
            message: '参数无变化'
          }
        }

        const response = await fetch('https://ws.waterism.tech:8090/api/update_hydromodel_params', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            session_id: props.sessionId,
            updates: updates
          })
        })

        if (!response.ok) {
          throw new Error(`参数更新失败: ${response.status}`)
        }

        const result = await response.json()
        
        return {
          success: true,
          message: `成功更新 ${Object.keys(updates.initial_state || {}).length + Object.keys(updates.parameters || {}).length} 个参数`
        }
      } catch (error) {
        console.error('应用参数变化失败:', error)
        return {
          success: false,
          message: `参数更新失败: ${error.message}`
        }
      }
    }

    return {
      messages,
      inputText,
      isThinking,
      thinkingText,
      messagesContainer,
      canSend,
      formatParamKey,
      formatTime,
      sendMessage,
      scrollToBottom
    }
  }
}
</script>

<style scoped>
.llm-chat {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f8f9fa;
}

/* 会话警告 */
.session-warning {
  margin: 20px;
  padding: 16px;
  background: linear-gradient(135deg, #fff3e0 0%, #ffe0b2 100%);
  border: 2px solid #ffb74d;
  border-radius: 12px;
  display: flex;
  gap: 12px;
  animation: warningPulse 2s ease-in-out infinite;
}

@keyframes warningPulse {
  0%, 100% {
    box-shadow: 0 2px 8px rgba(255, 183, 77, 0.3);
  }
  50% {
    box-shadow: 0 4px 16px rgba(255, 183, 77, 0.5);
  }
}

.warning-icon {
  font-size: 32px;
  flex-shrink: 0;
}

.warning-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.warning-title {
  font-size: 15px;
  font-weight: 600;
  color: #e65100;
}

.warning-text {
  font-size: 13px;
  color: #ef6c00;
  line-height: 1.6;
}

/* 头部 */
.llm-header {
  padding: 16px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-bottom: 1px solid #e4e7ed;
  flex-shrink: 0;
}

.llm-title {
  display: block;
  font-size: 16px;
  font-weight: 600;
  color: #fff;
  margin-bottom: 4px;
}

.llm-subtitle {
  display: block;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.8);
}

/* 消息列表 */
.llm-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.llm-message {
  display: flex;
  gap: 12px;
  animation: messageIn 0.3s ease-out;
}

@keyframes messageIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.msg-avatar {
  width: 36px;
  height: 36px;
  flex-shrink: 0;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 6px rgba(102, 126, 234, 0.3);
}

.llm-message.user .msg-avatar {
  background: linear-gradient(135deg, #43a047 0%, #388e3c 100%);
  box-shadow: 0 2px 6px rgba(67, 160, 71, 0.3);
}

.avatar-emoji {
  font-size: 20px;
}

.msg-content {
  flex: 1;
  max-width: 85%;
}

.msg-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 6px;
}

.msg-sender {
  font-size: 13px;
  font-weight: 600;
  color: #5f6368;
}

.msg-time {
  font-size: 11px;
  color: #9aa0a6;
}

.msg-text {
  padding: 14px 16px;
  border-radius: 12px;
  line-height: 1.6;
}

.user-text {
  background: linear-gradient(135deg, #1976d2 0%, #1565c0 100%);
  color: #fff;
  box-shadow: 0 2px 6px rgba(25, 118, 210, 0.25);
}

.ai-text {
  background-color: #fff;
  border: 1px solid #e8eaed;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.ai-section {
  display: block;
}

.ai-reply {
  font-size: 14px;
  color: #2c3e50;
  display: block;
}

/* 参数变化 */
.param-changes {
  padding: 12px;
  background: linear-gradient(135deg, #e3f2fd 0%, #e8eaf6 100%);
  border-radius: 8px;
  border-left: 3px solid #667eea;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 8px;
}

.title-icon {
  font-size: 16px;
}

.title-text {
  font-size: 13px;
  font-weight: 600;
  color: #5f6368;
}

.param-list {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.param-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 10px;
  background-color: rgba(255, 255, 255, 0.7);
  border-radius: 6px;
}

.param-key {
  font-size: 12px;
  font-weight: 500;
  color: #5f6368;
  font-family: monospace;
}

.param-arrow {
  font-size: 12px;
  color: #667eea;
}

.param-value {
  font-size: 13px;
  font-weight: 600;
  color: #667eea;
  font-family: monospace;
}

/* 解释说明 */
.explanation {
  padding: 12px;
  background-color: #fff7e6;
  border-radius: 8px;
  border-left: 3px solid #ffa940;
}

.explanation-text {
  font-size: 13px;
  color: #d46b08;
  line-height: 1.6;
  display: block;
}

/* 应用状态 */
.apply-status {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 12px;
  border-radius: 8px;
}

.apply-status.success {
  background-color: #f6ffed;
  border: 1px solid #b7eb8f;
}

.apply-status.error {
  background-color: #fff1f0;
  border: 1px solid #ffccc7;
}

.status-icon {
  font-size: 16px;
}

.status-text {
  font-size: 13px;
  font-weight: 500;
}

.apply-status.success .status-text {
  color: #52c41a;
}

.apply-status.error .status-text {
  color: #f5222d;
}

/* 思考中 */
.thinking-indicator {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
  padding: 14px 16px;
  background-color: #fff;
  border: 1px solid #e8eaed;
  border-radius: 12px;
}

.thinking-dots {
  display: flex;
  gap: 6px;
}

.thinking-dots .dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #667eea;
  animation: bounce 1.4s infinite;
}

.thinking-dots .dot:nth-child(2) {
  animation-delay: 0.2s;
}

.thinking-dots .dot:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes bounce {
  0%, 60%, 100% {
    transform: translateY(0);
  }
  30% {
    transform: translateY(-10px);
  }
}

.thinking-text {
  font-size: 13px;
  color: #5f6368;
  font-style: italic;
}

/* 输入区域 */
.llm-input-container {
  padding: 16px 20px;
  background-color: #fff;
  border-top: 1px solid #e4e7ed;
  flex-shrink: 0;
  display: flex;
  gap: 12px;
  align-items: flex-end;
}

.llm-input {
  flex: 1;
  min-height: 44px;
  max-height: 120px;
  padding: 12px 14px;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  font-size: 14px;
  color: #606266;
  resize: none;
  transition: all 0.3s;
}

.llm-input:focus {
  border-color: #667eea;
  outline: none;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
}

.llm-input:disabled {
  background-color: #f5f7fa;
  cursor: not-allowed;
}

.llm-send-btn {
  padding: 12px 20px;
  border: none;
  border-radius: 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 6px;
  box-shadow: 0 2px 6px rgba(102, 126, 234, 0.3);
}

.llm-send-btn:hover:not(.disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.llm-send-btn:active:not(.disabled) {
  transform: translateY(0);
}

.llm-send-btn.disabled {
  background: #c0c4cc;
  cursor: not-allowed;
  box-shadow: none;
}

.btn-icon {
  font-size: 16px;
  display: block;
}

.btn-text {
  display: block;
}

/* 滚动条 */
.llm-messages::-webkit-scrollbar {
  width: 6px;
}

.llm-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.llm-messages::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.llm-messages::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>

